package com.qfedu.hotelssm.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.qfedu.hotelssm.dao.ReturnsDao;
import com.qfedu.hotelssm.dto.ComplaitExportDat;
import com.qfedu.hotelssm.dto.ReturnsExportDto;
import com.qfedu.hotelssm.entity.Returns;
import com.qfedu.hotelssm.service.intf.ReturnsService;
import com.qfedu.hotelssm.util.StringUtil;
import com.qfedu.hotelssm.vo.PageBean;
import com.qfedu.hotelssm.vo.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;

/**
 * @author javaqjb
 * @date 2022/8/29
 */
@Service
public class ReturnsServiceImpl implements ReturnsService {

    @Autowired
    private ReturnsDao returnsDao;



    @Override
    public R save(Returns returns) {
        System.out.println(returns);
        if (returnsDao.save(returns) > 0) {
            return R.ok(returns.getId());
        } else {
            return R.fail();
        }
    }

    @Override
    public R update(Returns returns) {
        System.out.println(returns);
        if (returnsDao.update(returns) > 0) {
            return R.ok();
        } else {
            return R.fail();
        }
    }

    @Override
    public R delete(int id) {
        if (returnsDao.delete(id) > 0) {
            return R.ok();
        } else {
            return R.fail();
        }
    }

    @Override
    public R delIds(int[] ids) {
        if(returnsDao.delByIds(ids)>0){
            return R.ok();
        }else {
            return R.fail();
        }
    }

    @Override
    public List<ReturnsExportDto> all() {
        return returnsDao.all();
    }

    @Override
    public R upload(MultipartFile file) throws IOException {
        //1.接收文件， 获取文件内容
        //1.验证上传文件是否存在
        if(!file.isEmpty()){
            //2.解析Excel -EasyExcel
            //2.解析Excel数据
            List<Object> map= EasyExcel.read(file.getInputStream(), ReturnsExportDto.class , new ReadListener() {
                @Override
                public void invoke(Object o, AnalysisContext analysisContext) {}
                @Override
                public void doAfterAllAnalysed(AnalysisContext analysisContext) {}
            }).sheet().doReadSync();
            //3.Mybatis 实现批量新增
            if(returnsDao.saveBatch(map)>0){
                //4.返回
                return R.ok();
            }
        }
        return R.fail();
    }

    @Override
    public PageBean selectPage(String genre, int page, int limit) {
        if (StringUtil.isNotEmpty(genre)) {
            genre = "%"+genre+"%";
        }
        int startPage = (page - 1) * limit;
        return new PageBean((int) returnsDao.countEmp(genre), returnsDao.pageSelect(genre, startPage, limit));
    }

}
